<template>
  <div class="login-container">
    <div class="background-decoration"></div>
    <div class="login-content">
      <div class="login-box">
        <div class="system-title">
          <h1>社团管理系统</h1>
          <p class="subtitle">Club Management System</p>
        </div>
        <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="密码" show-password>
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item prop="code">
            <div class="captcha-container">
              <el-input v-model="loginForm.code" placeholder="验证码" class="captcha-input">
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
              </el-input>
              <div class="captcha-img" @click="refreshCaptcha">
                <img v-if="captchaUrl" :src="captchaUrl" alt="验证码" />
                <div v-else class="captcha-loading">加载中...</div>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="handleLogin" class="login-button">登录</el-button>
          </el-form-item>
          
          <div class="login-options">
            <router-link to="/register">没有账号？立即注册</router-link>
            <el-button type="text" @click="showResetDialog">忘记密码</el-button>
          </div>
        </el-form>
      </div>
      
      <!-- 重置密码对话框 -->
      <el-dialog v-model="resetDialogVisible" title="重置密码" width="30%">
        <el-form :model="resetForm" :rules="resetRules" ref="resetFormRef">
          <el-form-item prop="username" label="用户名">
            <el-input v-model="resetForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          
          <el-form-item prop="phone" label="手机号">
            <el-input v-model="resetForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          
          <el-form-item prop="real_name" label="真实姓名">
            <el-input v-model="resetForm.real_name" placeholder="请输入真实姓名"></el-input>
          </el-form-item>
          
          <el-form-item prop="id_card" label="身份证号">
            <el-input v-model="resetForm.id_card" placeholder="请输入身份证号"></el-input>
          </el-form-item>
          
          <el-form-item prop="password" label="新密码">
            <el-input v-model="resetForm.password" type="password" placeholder="请输入新密码" show-password></el-input>
          </el-form-item>
          
          <el-form-item prop="code" label="验证码">
            <div class="captcha-container">
              <el-input v-model="resetForm.code" placeholder="验证码" class="captcha-input"></el-input>
              <div class="captcha-img" @click="refreshResetCaptcha">
                <img v-if="resetCaptchaUrl" :src="resetCaptchaUrl" alt="验证码" />
                <div v-else class="captcha-loading">加载中...</div>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleResetPassword" :loading="resetLoading">确认重置</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'
import { userApi } from '../api'

const router = useRouter()
const loginFormRef = ref(null)
const resetFormRef = ref(null)
const loading = ref(false)
const resetLoading = ref(false)
const captchaUrl = ref('')
const resetCaptchaUrl = ref('')
const verifyCodeKey = ref('')
const resetVerifyCodeKey = ref('')
const resetDialogVisible = ref(false)

const loginForm = ref({
  username: '',
  password: '',
  code: '',
  codekey: ''
})

const resetForm = ref({
  username: '',
  phone: '',
  password: '',
  code: '',
  codekey: '',
  real_name: '',
  id_card: ''
})

const resetRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    // { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  real_name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  id_card: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    // { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ]
}

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

// 获取验证码
const getCaptcha = async () => {
  try {
    const response = await userApi.getKaptcha()
  
    
    // 将Blob转换为JSON
    const text = await response.text()
    const data = JSON.parse(text)
    
    if (data.code === 200 && data.data) {
      // 从base64字符串创建图片URL
      captchaUrl.value = `data:image/jpeg;base64,${data.data.image}`
      
      // 获取验证码key
      const verifyCode = data.data.verifyCode
      if (verifyCode) {
        verifyCodeKey.value = verifyCode
        loginForm.value.codekey = verifyCode
      }
    } else {
      ElMessage.warning('验证码获取异常，请刷新重试')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败')
  }
}

// 获取重置密码验证码
const getResetCaptcha = async () => {
  try {
    const response = await userApi.getKaptcha()
    
    // 将Blob转换为JSON
    const text = await response.text()
    const data = JSON.parse(text)
    
    if (data.code === 200 && data.data) {
      // 从base64字符串创建图片URL
      resetCaptchaUrl.value = `data:image/jpeg;base64,${data.data.image}`
      
      // 获取验证码key
      const verifyCode = data.data.verifyCode
      if (verifyCode) {
        resetVerifyCodeKey.value = verifyCode
        resetForm.value.codekey = verifyCode
      }
    } else {
      
      ElMessage.warning('验证码获取异常，请刷新重试')
    }
  } catch (error) {
    
    ElMessage.error('获取验证码失败')
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  getCaptcha()
}
// 刷新重置密码验证码
const refreshResetCaptcha = () => {
  getResetCaptcha()
}

// 显示重置密码对话框
const showResetDialog = () => {
  resetDialogVisible.value = true
  getResetCaptcha()
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await userApi.login(loginForm.value)
        if (res.code === 200) {
          // 存储用户信息到localStorage
          localStorage.setItem('userInfo', JSON.stringify(res.data))
          // 存储用户角色
          localStorage.setItem('role', res.data.role)
          // 存储用户ID
          localStorage.setItem('userId', res.data.id)
          
          ElMessage.success('登录成功')
          
          // 根据用户角色决定跳转目标
          if (res.data.role === '系统管理员') {
            router.push('/admin')
          } else if (res.data.role === '社团管理员') {
            router.push('/clubadmin') 
          } else {
            router.push('/home')
          }
        } else {
          ElMessage.error(res.message || '登录失败')
          // 验证码错误时刷新验证码并清空输入框
          if (res.message && res.message.includes('验证码')) {
            loginForm.value.code = ''
            getCaptcha()
          }
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败，请重试')
        // 发生错误时也刷新验证码
        loginForm.value.code = ''
        getCaptcha()
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置密码处理
const handleResetPassword = async () => {
  if (!resetFormRef.value) return
  
  await resetFormRef.value.validate(async (valid) => {
    if (valid) {
      resetLoading.value = true
      try {
        const res = await userApi.resetPassword(resetForm.value)
        if (res.code === 200) {
          ElMessage.success(res.message || '密码重置成功')
          resetDialogVisible.value = false
          resetForm.value = {
            username: '',
            password: '',
            code: '',
            codekey: ''
          }
        } else {
          ElMessage.error(res.message || '密码重置失败，请检查输入信息')
          // 验证码错误时刷新验证码并清空输入框
          if (res.message && res.message.includes('验证码')) {
            resetForm.value.code = ''
            getResetCaptcha()
          }
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '密码重置失败，请稍后重试')
        console.error(error)
        // 发生错误时也刷新验证码
        resetForm.value.code = ''
        getResetCaptcha()
      } finally {
        resetLoading.value = false
      }
    }
  })
}

onMounted(() => {
  getCaptcha()
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  position: relative;
  background: linear-gradient(135deg, #f7fafc 0%, #e3f6f5 100%);
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 20% 20%, rgba(100, 200, 180, 0.08) 0%, transparent 40%),
    radial-gradient(circle at 80% 80%, rgba(100, 200, 180, 0.08) 0%, transparent 40%),
    url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" stroke="rgba(100,200,180,0.05)" stroke-width="0.5" fill="none"/></svg>');
  background-size: cover, cover, 300px 300px;
  animation: backgroundFloat 20s linear infinite;
}

@keyframes backgroundFloat {
  from { background-position: 0 0, 0 0, 0 0; }
  to { background-position: 100px 100px, -100px -100px, 300px 300px; }
}

.login-content {
  position: relative;
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.login-box {
  width: 420px;
  padding: 40px 36px 32px 36px;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(100, 200, 180, 0.10);
  backdrop-filter: blur(10px);
  transition: transform 0.3s ease;
}

.login-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(100, 200, 180, 0.16);
}

.system-title {
  text-align: center;
  margin-bottom: 36px;
}

.system-title h1 {
  font-size: 30px;
  color: #22577a;
  margin-bottom: 8px;
  font-weight: 700;
  letter-spacing: 2px;
}

.subtitle {
  font-size: 15px;
  color: #38a3a5;
  margin: 0;
  letter-spacing: 1px;
}

.el-input {
  margin-bottom: 20px;
}

.el-input :deep(.el-input__wrapper) {
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(100, 200, 180, 0.05);
}

.el-button {
  border-radius: 10px;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  transition: all 0.3s;
}

.login-button {
  width: 100%;
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%);
  border: none;
  margin-top: 10px;
  color: #22577a;
}

.login-button:hover {
  background: linear-gradient(90deg, #b8e1dd 0%, #8fd6e1 100%);
  color: #38a3a5;
  transform: translateY(-1px);
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 18px;
  font-size: 14px;
}

.login-options a,
.login-options .el-button {
  color: #38a3a5;
  text-decoration: none;
  transition: color 0.3s ease;
  font-size: 14px;
  padding: 0;
  height: auto;
  font-weight: normal;
  background: none;
  border: none;
}

.login-options a:hover,
.login-options .el-button:hover {
  color: #22577a;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.captcha-input {
  flex: 1;
  margin-right: 12px;
}

.captcha-img {
  width: 144px;
  height: 40px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
  border: 1.5px solid #e3e8ee;
}

.captcha-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-loading {
  font-size: 12px;
  color: #909399;
}

.el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(100, 200, 180, 0.10);
}
.el-dialog__header {
  padding: 16px 24px;
  border-bottom: 1px solid #e3e8ee;
}
.el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #22577a;
}
.el-dialog__body {
  padding: 20px 24px;
}
.el-dialog__footer {
  padding: 12px 24px;
  border-top: 1px solid #e3e8ee;
}

::-webkit-scrollbar {
  width: 8px;
  background: #e3f6f5;
}
::-webkit-scrollbar-thumb {
  background: #b8e1dd;
  border-radius: 4px;
}
</style>